package com.jdew.thkj.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jdew.thkj.R;
import com.jdew.thkj.adapter.SharePictureAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.WrapContentLinearLayoutManager;
import com.jdew.thkj.onitemInterface.OnItemcheckedListener;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.ZXingUtils;
import com.jdew.thkj.wxapi.WechatShareManeger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class JDSharePictureActivity extends BaseActivity {
    @Bind(R.id.banner)
    ImageView banner;
    @Bind(R.id.share_name)
    TextView shareName;
    @Bind(R.id.share_price)
    TextView sharePrice;
    @Bind(R.id.share_before_price)
    TextView shareBeforePrice;
    @Bind(R.id.share_quan)
    TextView quan;
    @Bind(R.id.share_before_salume)
    TextView salume;
    @Bind(R.id.share_ercode)
    ImageView shareErcode;
    @Bind(R.id.shareView)
    View shareView;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.share)
    TextView share;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.er_view)
    RelativeLayout erView;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.names)
    TextView names;
    @Bind(R.id.s1)
    TextView s1;
    @Bind(R.id.n1)
    TextView n1;
    @Bind(R.id.s2)
    TextView s2;
    @Bind(R.id.n2)
    TextView n2;
    @Bind(R.id.lianjie)
    TextView lianjie;
    @Bind(R.id.copy)
    TextView copy;
    @Bind(R.id.onsale)
    TextView onsale;
    @Bind(R.id.preview)
    RelativeLayout preview;
    @Bind(R.id.shop)
    ImageView shop;
    @Bind(R.id.shopname)
    TextView shopname;
    @Bind(R.id.couple)
    TextView couple;
    @Bind(R.id.duanlian)
    TextView duanlian;
    @Bind(R.id.line)
    TextView line;
    private WechatShareManeger mShareManager;
    private Bitmap shareBitmap = null;
    private String h5;
    private String youhuiquan, ispinggou;
    private String price, beforeprice;
    private String volume;
    private String ptitle;
    private String shops;
    private List<String> imageList = new ArrayList<>();
    private SharePictureAdapter adapter;
    private int pos;
    private Dialog mShareDialog;
    public SharedPreferences sp;
    public SharedPreferences.Editor editor;

    @Override
    public int bindLayout() {
        return R.layout.activity_share_pic;
    }

    @Override
    public void initView(View view) {
        mShareManager = WechatShareManeger.getInstance(this);
        title.setText("分享预览");
        line.setVisibility(View.GONE);
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        adapter = new SharePictureAdapter(this, imageList);
        GetProductDetail();
        recycleView.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recycleView.setAdapter(adapter);
        adapter.map.put(0, true);
        adapter.setItemCheckedListener(new OnItemcheckedListener() {
            @Override
            public void onitemcheck(int position) {
                Glide.with(JDSharePictureActivity.this).load(imageList.get(adapter.pos)).into(banner);
            }
        });
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        share.setOnClickListener(this);
        copy.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.share: {
                showDialog();
            }
            break;
            case R.id.copy: {
                RegexValidateUtils.copyText(this, ptitle + "\n" + s1.getText().toString() + "\n" + n1.getText().toString() + "\n" + "【优惠券】  " + youhuiquan + "元" + "\n" + onsale.getText().toString() + "\n" + "点击下面的链接即可领券" + "\n" + h5);
                ToastUtils.getInstance(this).showMessage("复制成功");
            }
            break;
            default:
                break;
        }
    }

    /**
     * 显示分享弹出框
     */
    private void showDialog() {
        if (mShareDialog == null) {
            initShareDialog();
        }
        mShareDialog.show();
    }

    /**
     * 初始化分享弹出框
     */
    private void initShareDialog() {
        mShareDialog = new Dialog(this, R.style.dialog_bottom_full);
        mShareDialog.setCanceledOnTouchOutside(true);
        mShareDialog.setCancelable(true);
        Window window = mShareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_animation);
        View view = View.inflate(this, R.layout.layout_share, null);
        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preview.setVisibility(View.VISIBLE);
                if (mShareDialog != null && mShareDialog.isShowing()) {
                    mShareDialog.dismiss();
                }
            }
        });
        view.findViewById(R.id.wx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preview.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shareBitmap = RegexValidateUtils.getBitmapByView(shareView);
                        mShareManager.sharePicture(0, shareBitmap);
                    }
                }, 500);
            }
        });
        view.findViewById(R.id.friend_cricle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preview.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shareBitmap = RegexValidateUtils.getBitmapByView(shareView);
                        mShareManager.sharePicture(1, shareBitmap);
                    }
                }, 500);
            }
        });
        view.findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preview.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < imageList.size(); i++) {

                            if (i == pos) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        shareBitmap = RegexValidateUtils.getBitmapByView(shareView);
                                        RegexValidateUtils.saveBmp2Gallery(JDSharePictureActivity.this,shareBitmap);
                                    }
                                }).start();
                            } else {
                                final String url = imageList.get(i);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (!url.equals("") && null != url) {
                                            shareBitmap = RegexValidateUtils.returnBitmap(url);
                                            RegexValidateUtils.saveBmp2Gallery(JDSharePictureActivity.this,shareBitmap);
                                        }
                                    }
                                }).start();
                            }
                        }
                    }
                }, 500);
                Toast.makeText(JDSharePictureActivity.this, "图片保存成功，请进入相册查看", Toast.LENGTH_SHORT).show();
                preview.setVisibility(View.VISIBLE);
            }
        });
        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
    }


    public void GetProductDetail() {
        youhuiquan = getIntent().getStringExtra("quan");
        ispinggou = getIntent().getStringExtra("ispingou");
        price = getIntent().getStringExtra("price");
        beforeprice = Double.parseDouble(price) + Double.parseDouble(youhuiquan) + "";
        h5 = getIntent().getStringExtra("h5");
        volume = getIntent().getStringExtra("salume");
        ptitle = getIntent().getStringExtra("title");
        shops = getIntent().getStringExtra("shop");
        imageList = getIntent().getStringArrayListExtra("imageList");
        DecimalFormat df = new DecimalFormat("0.00");
        if (ispinggou.equals("yes")) {
            shareBeforePrice.setText(df.format(Double.parseDouble(beforeprice)));
            sharePrice.setText(df.format(Double.parseDouble(price)));
            n1.setText("【拼购价】  " + df.format(Double.parseDouble(price)) + "元");
            n2.setText("【拼购价】  " + df.format(Double.parseDouble(price)) + "元");
        } else {
            shareBeforePrice.setText(df.format(Double.parseDouble(beforeprice)));
            sharePrice.setText(df.format(Double.parseDouble(price)));
            n1.setText("【抢购价】  " + df.format(Double.parseDouble(price)) + "元");
            n2.setText("【抢购价】  " + df.format(Double.parseDouble(price)) + "元");
        }
        shareBeforePrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        salume.setText(volume);
        salume.setVisibility(View.INVISIBLE);
        s1.setText("【在售价】  " + df.format(Double.parseDouble(beforeprice)) + "元");
        s2.setText("【在售价】  " + df.format(Double.parseDouble(beforeprice)) + "元");
        couple.setText("【优惠券】  " + youhuiquan + "元");
        duanlian.setText("领券链接：" + h5);
        shareName.setText(ptitle);
        name.setText(ptitle);
        names.setText(ptitle);
        quan.setText(youhuiquan.replace(".00",""));
        shopname.setText("京东");
        adapter.setDataList(imageList);
        try {
            shareBitmap = ZXingUtils.createQRImage(h5, 300, 300);//自己写的方法
            if (shareBitmap != null) {
                shareErcode.setImageBitmap(shareBitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Glide.with(this).load(imageList.get(0)).into(banner);
        shop.setImageResource(R.mipmap.jd_source);
    }


    @Override
    protected void onResume() {
        super.onResume();
        preview.setVisibility(View.VISIBLE);
        shareView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != shareBitmap && !shareBitmap.isRecycled()) {
            shareBitmap.recycle();
            shareBitmap = null;
            System.gc();
        }
        ButterKnife.unbind(this);
    }

}
